import React, { Component } from 'react'
import moment from 'moment'
import { Link } from 'react-router-dom';
import axios from 'axios'
import qs from 'qs'
import { List, Avatar, Button, Skeleton ,Spin,Modal } from 'antd';
import Config from '../config'
import ReactEcharts from 'echarts-for-react';
import TweenOne from 'rc-tween-one';
import Children from 'rc-tween-one/lib/plugin/ChildrenPlugin';
require('./index.css')

TweenOne.plugins.push(Children);
export  const preventBackgroundScroll = (e: React.WheelEvent<HTMLDivElement>) => { 
  const target = e.currentTarget 
  if ( 
    (e.deltaY < 0 && target.scrollTop <= 0) || 
    (e.deltaY > 0 && target.scrollHeight - target.clientHeight - target.scrollTop <= 0) 
  ) { 
    e.stopPropagation() 
    e.preventDefault() 
  } 
}

export default class ReportForm extends Component {

  constructor(props) {
    super(props)
    this.state = {
      incomeAnimation:null,
      numberAnimation:null,
      hotel6Animation:null,
      hotel8Animation:null,
      hotelIncomeAnimation:null,
      hotelRoomAnimation:null,
      todayIncomeAnimation:null,
      topFiveNumList:[],
      topFiveIncomeList:[],
      todayIncome:'',
      todayNum:'',
      hotelState:{},
      hotelData:{},
      consumptionData:[],
      distributorNum:[],
      distributorIncome:[],
      distributorIncomes:[],
      hotelIncome:'',
      isData:false,
      loading:true,
      visible:false,
      todayIncomeTotal:''

    }
  }

  componentWillMount(){
    document.title = '景区报表中心'
    let _this=this;
    this.getData()
    setInterval(function(){
      _this.getData()
    },60000)

 
  }

  formatNumber(value) {
    value += '';
    const list = value.split('.');
    const prefix = list[0].charAt(0) === '-' ? '-' : '';
    let num = prefix ? list[0].slice(1) : list[0];
    let result = '';
    while (num.length > 3) {
      result = `,${num.slice(-3)}${result}`;
      num = num.slice(0, num.length - 3);
    }
    if (num) {
      result = num + result;
    }
    return `${prefix}${result}${list[1] ? `.${list[1]}` : ''}`;
  }

  componentDidMount() {
    // alert(this.formatNumber(123456789.05))
  }

  getData(){
    axios.get(`http://47.98.203.99:8180/app/MStatistics/getIndexData.do`,
    ).then(response => {
      console.log(response.data)
      let {todayIncome,todayNum,topFiveIncomeList,topFiveNumList,hotelState,hotelData,consumptionData,distributorIncome,distributorNum,hotelIncome} = response.data
      let todayIncomes = parseInt(todayIncome) + parseInt(hotelIncome)
      
      for(let i=0;i<distributorIncome.length;i++){
        for(let j=0;j<distributorNum.length;j++)
        if(distributorIncome[i]['name'] == distributorNum[j]['name']){
          distributorIncome[i]['num'] = distributorNum[j]['value']
        }
      }
      this.setState({
        todayIncome,todayNum,topFiveIncomeList,topFiveNumList,hotelState,hotelData,consumptionData,distributorNum,distributorIncome,hotelIncome,
        isData:true,loading:false
      },()=>{

        this.setState({
          incomeAnimation:{
            Children: { 
              value: parseInt(todayIncomes),floatLength: 2,
            }, 
            duration: 1000,
          },
          numberAnimation:{
            Children: { 
              value: parseInt(todayNum),floatLength: 0,
            }, 
            duration: 1000,
          },
          hotel6Animation:{
            Children: { 
              value: parseInt(hotelState.hotel_6_total-hotelState.hotel_6_empty),floatLength: 0,
            },
            duration: 1000,
          },
          hotel8Animation:{
            Children: { 
              value: parseInt(hotelState.hotel_8_total-hotelState.hotel_8_empty),floatLength: 0,
            }, 
            duration: 1000,
          },
        })
      })
    }).catch(error => {
        console.log(error)
    })
  }

  getOption(data,type) {
    let hotelState = this.state.hotelState
    return {
      tooltip: { 
        trigger: 'item', 
        position: [20, 20],
        backgroundColor: '#428bca', 
        //鼠标移动到图上面时，背景色 padding:15, //定义内边距 
        formatter: function(params) { 
        
        } 
      },
      series: [
        {
          name:'',
          type:'pie',
          radius: ['60%', '80%'],
          avoidLabelOverlap: false,
          animation :true,
          itemStyle: {
            normal: {
                color: function(params) {
                    var colorList = [
                      '#F5C565','#30C396','#FCCE10','#E87C25','#27727B',
                      '#FE8463','#9BCA63','#FAD860','#F3A43B','#60C0DD',
                      '#D7504B','#C6E579','#F4E001','#F0805A','#26C0C0'
                    ];
                    return colorList[params.dataIndex]
                },
                label: {
                    show: true,
                    position: 'top',
                    formatter: '{b}\n{c}'
                }
            }
        },
        label: {
          normal: {
              show: false,
              position: 'inside',
          },
          emphasis: {
              show: true,
              label: {
                show: true,
                position: 'top',
                formatter: '{b}\n{c}'
            },
              textStyle: {
                  fontSize: '12',
                  fontWeight: 'bold'
              }
          }
        },
          labelLine: {
              normal: {
                  show: false
              }
          },
          data:[
              {value:hotelState[`${type}_empty`], name:'空房/间'},
              {value:parseInt(hotelState[`${type}_total`]-hotelState[`${type}_empty`]), name:'已住/间'},
          ]
        }
      ]
    }
  };

  getAxisOption(){
    let hotelData = this.state.hotelData
    return {
      tooltip: {
          trigger: 'axis',
          axisPointer: {
              type: 'cross',
              label: {
                  backgroundColor: '#283b56'
              }
          }
      },
      height:80,
      width:'75%',
      padding:[2],
      textStyle:{
        fontSize:9,
        height:5
      },
      legend: {
        data:['收入', '房间数'],
        left:10,
        top:10,
        padding:10,
        itemHeight: 14, 
      },
      xAxis: [
        {
          type: 'category',
          boundaryGap: true,
          data: (function (){
            let fiveDayString = hotelData.fiveDayString
            var res = [];
            var len = 0;
            while (len < fiveDayString.length) {
              console.log(fiveDayString[len])
                res.push(moment(fiveDayString[len]).format('MM-DD'));
                len++;
            }
            return res;
          })(),
          nameTextStyle:{
            fontSize:8
          }
        },
        {
            type: 'category',
            boundaryGap: true,
            data: []
        }
      ],
      yAxis: [
        {
          type: 'value',
          scale: true,
          name: '间',
          max: 120,
          min: 0,
          splitNumber:4,
          nameGap:4,
          boundaryGap: [0.2, 0.2],
          nameTextStyle:{
            fontSize:10
          }
        },
        {
          type: 'value',
          scale: true,
          name: '元',
          nameGap:4,
          max: 30000,
          splitNumber:4,
          min: 0,
          boundaryGap: [0.2, 0.2],
          nameTextStyle:{
            fontSize:10
          }
        }
      ],
      series: [
        {
          name:'收入',
          type:'bar',
          xAxisIndex: 1,
          yAxisIndex: 1,
          barWidth:'45%',
          itemStyle:{
            color:'#30C396'
          },
          label:{
            show:true,
            position :'top',
            fontSize:12
          },
          data:hotelData.fiveDayIncome
        },
        {
          name:'房间数',
          type:'line',
          itemStyle:{
            color:'#F5C565'
          },
          data:hotelData.fiveDayNum
        }
      ]
    }
  }

  getTicketOption(type){
    let topFiveList = type === 'FiveNum' ? this.state.topFiveNumList  : this.state.topFiveIncomeList
    return {
      tooltip : {
          trigger: 'item',
          formatter: "{b} : {c} ({d}%)",
          position:['30%',70]
      },
      legend: {
        orient: 'vertical',
        left: '5%',
        data:(function (){
          var res = [];
          var len = topFiveList.length;
          for(let i=0;i<len;i++){
            res.push(topFiveList[i]['name'])
          }
          return res
        })(),
        itemWidth:10,
        itemHeight:5,
        formatter: function (params) {   
            let n = topFiveList.length
            for(let i=0;i<n;i++){
              if(topFiveList[i]['name'] == params){
                return `${params}  ${topFiveList[i]['value']} ${type === 'FiveNum' ? '张':'元'}`
              }
            }
        }, 
        textStyle:{
          fontSize:10
        }
      },
      series : [
        {
          name: '',
          type: 'pie',
          radius : '75%',
          center: ['78%', '50%'],
          data:topFiveList,
          label:{
            fontSize:10
          },
          itemStyle: {
            emphasis: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
            },
            normal: {
              color: function(params) {
                  var colorList = [
                    '#F5C565','#7d82e8','#D7504B','#C6E579','#26C0C0',
                    '#FE8463','#9BCA63','#FAD860','#F3A43B','#60C0DD',
                    '#D7504B','#C6E579','#F4E001','#F0805A','#26C0C0'
                  ];
                  return colorList[params.dataIndex]
              },
              label: {
                  show: false,
                  position: 'top',
                  fontSize:10,
                  formatter: '{b}\n{c}({d}%)'
              }
            }
          },
          emphasis:{
            label:{
              fontSize:10
            }
          }
        }
      ]
    }
  }

  html(){
    let {hotelState,consumptionData,topFiveIncomeList,topFiveNumList,todayIncome,todayNum} = this.state
    let isConsumption = false
    consumptionData.map((item, index) => {
      parseInt(item.totalIncome) > 0 && (isConsumption = true)
    })
    let htmlData = []
    htmlData.push(
      <div className="ReportBox">
        <div className="ReportItem clearfix boxS pad15 bgfff">
          <div class="ReportItemLeft bord-r pos-rel ">
            <span className="fs-10 clor1 pos-abs delt" onClick={this.showModal.bind(this,true)} >详细</span>
            <p className="fw-6">今日收入</p>
            {
              parseInt(todayIncome)>0?
              <p className="price">
              <TweenOne animation={this.state.incomeAnimation} className="price" style={{display: "-webkit-inline-box"}}></TweenOne>
              <span className="fs-10 clor1"> 元</span>
              </p>:<div className="padt15 colb3">暂无统计</div>
            }
          </div>
          <div class="ReportItemRight">
            <p className="fw-6">今日人数</p>
            {
              parseInt(todayNum)>0?
              <p className="price">
                <TweenOne animation={this.state.numberAnimation} className="price col30" style={{display: "-webkit-inline-box"}}></TweenOne>
                <span className="fs-10 clor1"> 人</span>
              </p>:<div className="padt15 colb3">暂无统计</div>
            }
          </div>
        </div>

        <div className="ReportItem clearfix">
          <div class="ReportItemLeft boxS w49 br-5 pad5 bgfff">
            <p className="fw-6">养心苑</p>
            <div style={{height:105}} className="pos-rel">
              <ReactEcharts
                ref = "pie1"
                style={{height:110}}
                option={this.getOption(hotelState,'hotel_6')}
                notMerge={true}
                lazyUpdate={true}
                theme={"theme_name"}
              />
              <div className="pos-abs top36 pieDiv" id="pie1">
                <p >
                  <TweenOne animation={this.state.hotel6Animation} className="fs-disCon" ></TweenOne>/
                  <span className="cl-fw">{hotelState.hotel_6_total}</span>
                </p>
              </div>
            </div>
          </div>
          <div class="ReportItemRight boxS w49 br-5 pad5 bgfff">
            <p className="fw-6">青春驿站</p>
            <div style={{height:105}} className="pos-rel" >
              <ReactEcharts
                ref = "pie2"
                style={{height:110}}
                option={this.getOption(hotelState,'hotel_8')}
                notMerge={true}
                lazyUpdate={true}
                theme={"theme_name"}
              />
              <div className="pos-abs top36 pieDiv" id="pie2">
                <p >
                  <TweenOne animation={this.state.hotel8Animation} className="fs-disCon" ></TweenOne>/
                  <span className="cl-fw">{hotelState.hotel_8_total}</span>
                </p>
              </div>
            </div>
          </div>
        </div>

        <div className="ReportItem clearfix boxS pad15 bgfff" style={{padding:'8px 0 0 0'}}>
          <p className="te-cen fw-6">酒店近五天收入及入住房间数</p>
          <ReactEcharts
            ref = "pie2"
            style={{height:180}}
            option={this.getAxisOption()}
            notMerge={true}
            lazyUpdate={true}
            theme={"theme_name"}
          />
        </div>

          { isConsumption&&<div className="ReportItem clearfix boxS pad15 bgfff" style={{padding:'8px 0 0 0'}}>
            <p className="te-cen fw-6">二次消费项目每日预订/收入/排队人数</p>
            <div className="mr-10">
              <p className='tableHear clearfix tableHearFs' >
                <span class="erName"></span>
                <span>已售</span>
                <span>收入</span>
                <span>排队人数</span>
              </p>
              {
                consumptionData.map((item, index) => (
                  parseInt(item.totalIncome) > 0 ? <p className='tableHear clearfix '>
                    <span class="erName">{item.consumptionName.length>5?`${item.consumptionName.substr(0, 5)}..`:item.consumptionName}<i className="ericon">|</i></span>
                    <span>{item.totalNum}</span>
                    <span>{item.totalIncome}</span>
                    <span>{item.lineNum}</span>
                  </p>:null
                ))
              }
            </div>
          </div>
        }

        <div className="ReportItem clearfix boxS pad15 pos-rel bgfff" style={{padding:'8px 0 0 0'}}>
          <p className="te-cen fw-6">渠道销量排行榜</p>
          {topFiveNumList.length>0&&<div className="pos-abs more" onClick={this.showModal.bind(this,false)}>查看更多</div>}
          { topFiveNumList.length>0 ?
            <div className="mr-10">
              <ReactEcharts
                ref = "pie2"
                style={{height:110}}
                option={this.getTicketOption('FiveNum')}
                notMerge={true}
                lazyUpdate={true}
                theme={"theme_name"}
              />
            </div>:<div className="mr-texc colb3">暂无统计数据</div>}
        </div>
        <div className="ReportItem clearfix boxS pad15 pos-rel bgfff" style={{padding:'8px 0 0 0'}}>
          <p className="te-cen fw-6">渠道销售排行榜</p>
          {topFiveIncomeList.length>0&&<div className="pos-abs more" onClick={this.showModal.bind(this,false)}>查看更多</div>}
          {
            topFiveIncomeList.length>0 ?
            <div className="mr-10">
              <ReactEcharts
                ref = "pie2"
                style={{height:110}}
                option={this.getTicketOption('income')}
                notMerge={true}
                lazyUpdate={true}
                theme={"theme_name"}
              />
            </div>:<div className="mr-texc colb3">暂无统计数据</div>
          }
            
        </div>
      </div>
    )
    return htmlData
  }

  showModal = (type) => {
    document.getElementById("bg").style.overflowY ="hidden";
    let {distributorIncome,hotelState,hotelIncome,todayIncome} = this.state
    let hotelRoom = (parseInt(hotelState.hotel_6_total)-parseInt(hotelState.hotel_6_empty)) + (parseInt(hotelState.hotel_8_total)-parseInt(hotelState.hotel_8_empty))
    let todayIncomes = parseInt(todayIncome) + parseInt(hotelIncome)
    for(let i=0;i<distributorIncome.length;i++){
      this.setState({
        [`incomeAnimation${i}`]: {
          Children: { 
            value: parseInt(distributorIncome[i]['value']),floatLength: 2,
          }, 
          duration: 1000,
        },
        [`numAnimation${i}`]: {
          Children: { 
            value: parseInt(distributorIncome[i]['num']),floatLength: 0,
          }, 
          duration: 1000,
        },
        hotelIncomeAnimation:{
          Children: { 
            value: parseInt(hotelIncome),floatLength: 2,
          }, 
          duration: 1000,
        },
        hotelRoomAnimation:{
          Children: { 
            value: parseInt(hotelRoom),floatLength: 0,
          }, 
          duration: 1000,
        },
        todayIncomeAnimation:{
          Children: { 
            value: parseInt(todayIncome),floatLength: 2,
          }, 
          duration: 1000,
        },
        incomeAnimation:{
          Children: { 
            value: parseInt(todayIncomes),floatLength: 2,
          }, 
          duration: 1000,
        },
        todayIncomeTotal:type

      },()=>{
        this.setState({visible: true})
      });
    }
  }

  handleOk = (e) => {
    console.log(e);
    this.setState({
      visible: false,
      todayIncomeTotal:false
    });
  }

  handleCancel = (e) => {
    console.log(e);
    this.setState({
      visible: false,
      todayIncomeTotal:false
    });
  }

  render() {
    let {isData,distributorNum,distributorIncome,todayIncomeTotal} = this.state
    return (
      <div style={{ marginBottom: 20 }} id="bg">
        <Spin spinning={this.state.loading} style={{width:'100%',position: 'fixed',top: '48%'}} />
        {isData&&this.html()}
        <Modal
          title={todayIncomeTotal ? "渠道销量及总收入统计表" : "渠道销量及实际收入统计表"}
          visible={this.state.visible}
          onOk={this.handleOk}
          footer={
            todayIncomeTotal ? <p className='tableHear clearfix '>
              <span class="wid30 fs-9"></span>
              <span class="w26 clo-fw">总计</span>
              <span class="w30 fs-9"><TweenOne animation={this.state.incomeAnimation} className="fs-disCon fs-20 colf90" ></TweenOne> 元</span>
            </p> : null
          }
          destroyOnClose
          maskStyle={{overflowY:'hidden'}}
          style={{padding:0}}
          onCancel={this.handleCancel}
        >
          <div className="ReportItem clearfix  bgfff"  style={{marginBottom:0}}>
            <div className="mr-10">
              <p className='tableHear clearfix tableHearFs mrb10' >
                <span class="erName w26"></span>
                <span class="w30">实际收入</span>
                <span class="w27">已售</span>
              </p>
              <div className="" onWheel = { preventBackgroundScroll }>
                {
                  distributorIncome.map((item, index) => (
                    <p className='tableHear clearfix '>
                      <span class="w26">{item.name}</span>
                      <span class="w30 fs-9"><TweenOne animation={this.state[`incomeAnimation${index}`]} className="fs-disCon fs-16 colf90" ></TweenOne> 元</span>
                      <span class="w27 fs-9"><TweenOne animation={this.state[`numAnimation${index}`]} className="fs-disCon fs-16" ></TweenOne> 人</span>
                    </p>
                  ))
                }
              </div>
              <p className='tableHear clearfix mart10'>
                <span class="wid30 fs-9"></span>
                <span class="w26 clo-fw">小计</span>
                <span class="w30 fs-9"><TweenOne animation={this.state.todayIncomeAnimation} className="fs-disCon fs-20 colf90" ></TweenOne> 元</span>
                
              </p>
              {
                todayIncomeTotal&&
                <div className="mar32-12">
                  <p className='tableHear clearfix tableHearFs mrb10' >
                    <span class="erName w26"></span>
                    <span class="w30">预计收入</span>
                    <span class="w27">已售</span>
                  </p>
                  <p className='tableHear clearfix '>
                    <span class="w26">酒店</span>
                    <span class="w30 fs-9"><TweenOne animation={this.state.hotelIncomeAnimation} className="fs-disCon fs-16 colf90" ></TweenOne> 元</span>
                    <span class="w27 fs-9"><TweenOne animation={this.state.hotelRoomAnimation} className="fs-disCon fs-16" ></TweenOne> 间</span>
                  </p>
                </div>
              }
              
            </div>
          </div>
        </Modal>
      </div>
    )
  }
}
